import { AfterViewChecked, Component, Injector, ViewChild, OnInit } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { OutsourcingWorkFlowViewDto, OutsourcingWorkFlowServiceProxy, ProcessingOrderServiceProxy, UserServiceProxy, ProcessingOrderStepUserDto, WorkflowServiceProxy, ProcessingOrderDto, ProcessingViewDto, ProcessingOrderInputDto, OutsouringServiceProxy } from '@shared/service-proxies/service-proxies';

import { SelectItem, SelectItemGroup } from 'primeng/api';

@Component({
    selector: 'OrderCrucialProcessingCreate',
    templateUrl: './OrderCrucialProcessingCreate.component.html',
    styleUrls: ['./OrderCrucialProcessingCreate.component.css']
})
export class OrderCrucialProcessingCreateComponent extends AppComponentBase implements OnInit {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('teskdataTable') teskdataTable: Table;
    // @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    filterText = '';
    selectedCar3: string;
    detailsprimengTableHelper: PrimengTableHelper;
    _processingViewDto: ProcessingViewDto[];
    clonedOutsourcings: { [s: number]: ProcessingViewDto; } = {};
    _processingOrder: ProcessingOrderDto = new ProcessingOrderDto();
    workflow: OutsourcingWorkFlowViewDto;
    stepusers: ProcessingOrderStepUserDto;
    users: SelectItem[];

    SupplierAyy: SelectItem[];

    selectProcessingViewDto: ProcessingViewDto[];
    index = 0;
    constructor(injector: Injector,
        private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
        private _outSourcingServiceProxy: OutsouringServiceProxy,
        private _userService: UserServiceProxy,
        private _processingOrderServiceProxy: ProcessingOrderServiceProxy,
        private _workflowService: WorkflowServiceProxy
    ) {
        super(injector);
        this.detailsprimengTableHelper = new PrimengTableHelper();
        this.stepusers = new ProcessingOrderStepUserDto();
    }

    ngOnInit(): void {


    }

    show(): void {
        this.selectProcessingViewDto = new Array<ProcessingViewDto>();
        this._userService.getAllUserForDropDown2().subscribe(resultdata => {
            console.log(resultdata);
            this.users = resultdata;
        });
        this.active = true;
        this.modal.show();
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }
    onShown(): void {

    }
    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._outSourcingworkflowServiceProxy.getOutsourcingFormModelByCodeAsync(
            1,
            this.filterText,
            'Code',
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                console.log(result);
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
                _.forEach(result.items, viewItem => {
                    if (viewItem.workflowId !== '') {
                        console.log(viewItem.workflowId);
                        this._workflowService.getWorkflowByWorkflowid(viewItem.workflowId)
                            .subscribe(workflowtype => {
                                viewItem.applyType = workflowtype;
                            });
                    } else {
                        viewItem.applyType = '-';
                    }
                });
            });
    }

    //依据申请单获取任务
    SelectTask(record) {
        console.log(record);
        let _supplier = record.supplierUnit.split(',');
        this.SupplierAyy = new Array();
        this.SupplierAyy.push({ label: '请选择供方', value: '请选择供方' });
        _.forEach(_supplier, viewItem => {
            console.log(viewItem);
            this.SupplierAyy.push({ label: viewItem, value: viewItem });
        });
        this._processingOrder.supplierUnit = this.SupplierAyy[0].value;

        this.workflow = record;
        this._processingOrder.requisitionCode = record.code;
        this._outSourcingServiceProxy.getOutsourcingByWorkFlowIdAsync(record.workflowId).subscribe(dto => {
            console.log(dto);
            this._processingViewDto = dto;

            _.forEach(dto, viewItem => {
                console.log(viewItem.workflowId);
                this._processingOrderServiceProxy.getProcessingAmountForTaskId(viewItem.taskForModelId, record.code)
                    .subscribe(amount => {
                        viewItem.appliedAmount = amount;
                    });
            });


        });

        this._outSourcingworkflowServiceProxy.buildProcessingOrderCodeByOutsourcingCode(record.code).subscribe(code => {
            this._processingOrder.orderCode = code;
        });
        this.index = 1;
        console.log(this.index);
    }
    supplierChange(evt): void {

        console.log(evt.value);

        let newList = new Array();
        console.log(this._processingViewDto);
        _.forEach(this._processingViewDto, viewItem => {
            console.log(viewItem.supplierName);
            if (viewItem.supplierName === evt.value) {

                newList.push(viewItem);
            }
        });
        console.log(newList);
        this.detailsprimengTableHelper.totalRecordsCount = newList.length;
        this.detailsprimengTableHelper.records = newList;
        this.detailsprimengTableHelper.hideLoadingIndicator();

    }

    handleChange(e) {
        this.index = e.index;
        console.log(this.index);
    }


    onRowEditInit(quotationmodel: ProcessingViewDto) {
        console.log(quotationmodel);
        quotationmodel.processingAmount = quotationmodel.outsouringAmount;
        this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
    }

    onRowEditSave(quotationmodel: ProcessingViewDto) {
        console.log(quotationmodel);
        if (quotationmodel.outsouringAmount > 0) {
            delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];

            let _current = this.selectProcessingViewDto.find((element) => (element.taskForModelId == quotationmodel.taskForModelId));
            if (_current === undefined) {
                quotationmodel.processingAmount = quotationmodel.outsouringAmount;
                this.selectProcessingViewDto.push(quotationmodel);
            } else {
                _current.progressrequest = quotationmodel.progressrequest;
                _current.materialsupply = quotationmodel.materialsupply;
                _current.unitprice = quotationmodel.unitprice;
                _current.explain = quotationmodel.explain;
            }

        } else {
            this.notify.info('申请数量不能小于0');
        }
    }

    onRowEditCancel(quotationmodel: ProcessingViewDto, index: number) {
        console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
        this._processingViewDto[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
        delete this._processingViewDto[quotationmodel.taskForModelId];
    }

    save() {
        let input = new ProcessingOrderInputDto();
        // tslint:disable-next-line: triple-equals
        if (this.workflow.applyType == '一般过程外协申请') {
            input.workFlowName = '一般过程外包加工申请';
            // tslint:disable-next-line: triple-equals
        } else if (this.workflow.applyType == '关键过程外协申请') {
            input.workFlowName = '关键过程外包加工申请';
        }
        console.log(this.selectProcessingViewDto);
        if (this.selectProcessingViewDto.length === 0) {
            this.notify.info('未选择加工单内容');
            this.saving = false;
            return;
        }

        //判断审批用户是否设置
        if (!this.stepusers.outsourcingPlanned) {
            this.notify.info('请选择外协计划员');
            this.saving = false;
            return;
        }
        if (!this.stepusers.modelManagerPlanned) {
            this.notify.info('请选择型号主管计划员');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionLeader) {
            this.notify.info('计划生产处主管处长');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionDirector) {
            this.notify.info('计划生产处处长');
            this.saving = false;
            return;
        }

        input.stepUserDto = this.stepusers;
        input.processingOrderDto = this._processingOrder;
        input.processingViewDtos = this.selectProcessingViewDto;
        this.saving = true;

        console.log(input);
        this._outSourcingworkflowServiceProxy.createOrUpdateProcessingWorkFlow(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.close();
            });
    }

}
